// pages/patient/personalinfo/index.js
import { isyyyyMMddDate,isPoneAvailable } from "./../../../utils/util";
import { post } from "./../../../api/api"
import Toast from "./../../../miniprogram/miniprogram_npm/@vant/weapp/toast/toast"
import {checkValidResData} from "./../../../utils/checknull";

Page({
  data: {
    // about user info
    imgsrc: "",
    name: "",
    birth: "",
    sex: "男", // 0 for male && 1 for female
    idtype: "证件类型",
    identifynum: "", // 证件号码
    relation: "本人",
    phonenumber: "",
    defaultUser: true,

    value: "",
    sexcolumns: ['男', '女'],
    idtypecolumns: ["居民身份证", "护照"],
    realtioncolumns: ["本人", "亲属"],
    showpop: 0,

    openid: null
  },

  /**
   * get user info from server
   */
  onLoad: async function (options) {
    let openid = wx.getStorageSync('openid');
    
    if (openid == "" || openid == null || openid == undefined) {
      // unlogin,has no openid
      Toast('未登录')
      return;
    }
    this.setData({
      imgsrc: wx.getStorageSync("avatarUrl"),
      sex: wx.getStorageSync("gender") == 0 ? "男" : "女",
      openid: openid
    })

    // get other user info from server
    try {
      let pres = await post('/user/info', {openid: openid});
      console.log(pres);
      if(pres.statusCode != 200)
        throw '网络错误'
      if(pres.data.rescode != 200)
        throw '服务器错误'
      
      this.setData({
        imgsrc: pres.data.imgsrc,
        name: pres.data.name,
        birth: pres.data.birth,
        sex: pres.data.sex == '0' ? '男' : '女',
        idtype: checkValidResData(pres.data.idtype) ? pres.data.idtype : '证件类型',
        identifynum: pres.data.identifynum,
        relation: pres.data.relation,
        phonenumber : pres.data.phonenumber,
        defaultUser: pres.data.defaultUser
      })
    } catch (ex) {
      console.log(ex);
      Toast(ex);
    }
  },

  /**
   * 默认就诊人的switch事件处理
   */
  onChangeSwitch: function () {
    let newswith = !this.data.defaultUser;
    this.setData({
      defaultUser: newswith
    })
  },

  // 弹出层、显示picker
  showPop: function (e) {
    this.setData({
      showpop: Number(e.target.dataset.ix)
    });
  },

  // 弹出层选择
  onChange: function (e) {
    const { picker, value, index } = e.detail;
    if (e.target.dataset.ix == 1) {
      console.log('性别');
      this.setData({
        sex: value
      })
    } else if (e.target.dataset.ix == 2) {
      console.log('证件类型');
      this.setData({
        idtype: value
      })
    } else if (e.target.dataset.ix == 3) {
      console.log('关系');
      this.setData({
        relation: value
      })
    }
  },

  // 关闭弹出层
  onClose: function () {
    this.setData({
      showpop: 0
    })
  },

  // 检查所有的内容是否都已经填写了
  checkValidParam: function(){
    if (this.data.name == "")
      return '姓名为必填';
    if (this.data.phonenumber == "")
      return '电话号码为必填';
    if(isPoneAvailable(this.data.phonenumber) == false)
      return '手机号码格式错误';
    if (this.data.birth == "")
      return '出生日期为必填项';
    if (isyyyyMMddDate(this.data.birth) == false)
      return '出生日期格式应该为yyyy-MM-dd';
    if (this.data.idtype == "证件类型")
      return '请选择证件类型';
    if (this.data.identifynum == "")
      return '证件号码为必填项';
    return null
  },

  PostPatientInfo: async function () {
    let sendData = {
      openid: this.data.openid,
      name: this.data.name,
      birth: this.data.birth, // yyyy-MM-dd
      sex: this.data.sex == "男" ? 0 : 1,
      idtype: this.data.idtype,
      identifynum: this.data.identifynum,
      relation: this.data.relation,
      phonenumber: this.data.phonenumber,
      defaultUser: this.data.defaultUser,
    }

    try {
      let res = await post("/user/changeinfo", sendData);
      if (res.statusCode != 200) {
        throw '网络错误';
      }
      if (res.data.rescode != 200) {
        // server error
        throw '服务器错误'
      } else {
        // save success
        return 200;
      }
    } catch (ex) {
      console.log(ex);
      return ex;
    }
  },

  // 提交
  handleSubmit: async function () {
    // 判断是否必填的时候都填了，是的话就提交
    if(this.data.openid == null){
      Toast('未登录');
      return;
    }
    let checkres = this.checkValidParam();
    if (checkres != null) {
      // Toast
      Toast(checkres);
      return;
    }
    let res = await this.PostPatientInfo();
    if(res == 200){
      Toast('保存成功');
      setTimeout(()=>{
        wx.switchTab({
          url: '/pages/tarbarpages/personal/index/index',
        })
      },500)
      
    } else {
      Toast(res);
    }
  },
})